import { ref } from "vue";
import type { Ref } from "vue";
import { fromEvent, useObservable } from "@vueuse/rxjs";
import { debounceTime, distinctUntilChanged, map } from "rxjs";
import moment from "moment/moment";

export interface Task {
  id: string;
  content: string;
  createTime: string;
  status: boolean;
}
export function useOpen() {
  const open = ref<boolean>(false);

  const changeOpen = () => {
    open.value = !open.value;
  };

  return {
    open,
    changeOpen,
  };
}

export function useInput(input: Ref<HTMLElement>) {
  const inputStr = useObservable(
    fromEvent(input, "input").pipe(
      map((e) => (e.target as HTMLInputElement).value),
      debounceTime(200),
      distinctUntilChanged()
    )
  );
  return inputStr;
}

export interface ShowDialogType {
  show: boolean;
}
export function useSchedulerDialog() {
  const showDialog = ref<ShowDialogType>({
    show: false,
  });
  const currentTask = ref<Task>();

  const openDialog = (task: Task) => {
    currentTask.value = task;
    showDialog.value.show = true;
  };

  const closeDialog = () => (showDialog.value.show = false);

  return {
    showDialog,
    openDialog,
    closeDialog,
    currentTask,
  };
}

export function useTasks() {
  const tasks = ref<Task[]>([
    {
      id: crypto.randomUUID(),
      content: "Hello World",
      createTime: moment().format("YYYY-MM-DD HH:mm:ss"),
      status: true,
    },
  ]);

  const addTask = (content: string) => {
    tasks.value?.push({
      id: crypto.randomUUID(),
      content,
      createTime: moment().format("YYYY-MM-DD HH:mm:ss"),
      status: false,
    });
  };

  const removeTask = (id: string) => {
    tasks.value = tasks.value?.filter((task) => task.id !== id);
  };

  const changeStatus = (id: string, done: boolean) => {
    tasks.value = tasks.value?.map((task) => {
      if (task.id === id) {
        task.status = done;
      }
      return task;
    });
  };

  const queryTask = (id: string) => {
    return tasks.value?.find((task) => task.id === id);
  };

  return {
    tasks,
    addTask,
    removeTask,
    changeStatus,
    queryTask,
  };
}
